/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.gui.client;

import com.google.gwt.core.client.*;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.rpc.*;

import com.google.gwt.user.client.Window;

import nfse.gui.config.*;
import nfse.gui.query.*;

import com.gwtext.client.widgets.layout.*;
import com.gwtext.client.widgets.*;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.*;

/**
 * Entry point classes define <code>onModuleLoad()</code>.loadQueryButton
 */
public class NetFSEClient implements EntryPoint, PopupListener {

	public final static int UI_MODE_CLASSIC = 1;

	public static int UI_MODE = UI_MODE_CLASSIC;

	public static final int FIELD_DST_IP = 1;

	/***************************************************************************
	 * Field identifier for destination IP addresses
	 */
	public static final int FIELD_SRC_IP = 2;

	/***************************************************************************
	 * Field identifier for TCP port use by destination host (i.e. destination
	 * port)
	 */
	public static final int FIELD_DST_PORT = 3;

	/***************************************************************************
	 * Field identifier for start timestamp
	 */
	public static final int FIELD_START_TS = 4;

	/***************************************************************************
	 * Field identifier for packets sent by the source host (i.e. source
	 * packets)
	 */
	public static final int FIELD_SRC_PKTS = 10;

	/***************************************************************************
	 * Field identifier for record durations
	 */
	public static final int FIELD_DURATION = 11;

	/***************************************************************************
	 * Field identifier for IP protocol
	 */
	public static final int FIELD_PROTOCOL = 12;

	public static final int FIELD_BYTES = 13;

	public static final int FIELD_PACKETS = 14;

	public static String QUERY_URL = GWT.getModuleBaseURL() + "service";

	public static String CONFIG_URL = GWT.getModuleBaseURL() + "configs";

	public static String REPORT_URL = GWT.getModuleBaseURL() + "reports";

	public static void redirectToHome() {
		//if (NetFSEClient.UI_MODE == UI_MODE_CLASSIC)
		//	redirect("classic.html");
	}

	// redirect the browser to the given url
	public static native void redirect(String url)/*-{
		$wnd.location = url;
	}-*/;

	public static void showGenericDialog(String title, String html) {
		showGenericDialog(title, html, null);
	}

	public static void showGenericDialog(String title, String html,
			Widget sender) {
		MessageBox.alert(title, html);
	}

	AnalysisTab analysisTab = new AnalysisTab(this);

	SearchTab searchTab = new SearchTab(this);

	SearchHistoryTab searchHistoryTab = new SearchHistoryTab(this);

	TimelineTab timelineTab = new TimelineTab(this);

	SearchResultsTab searchResultsTab = new SearchResultsTab(this);

	com.gwtext.client.widgets.TabPanel tabs = null;

	final ConfigurationTab configurationTab = new ConfigurationTab(this);

	Panel configurationPanel = new Panel();

	private int[] types = new int[0];

	private int[] typeIdxs = new int[0];

	private String[] typeNames = new String[0];

	// 6000 is the time in seconds for dashboardRefreshFrequency
	final HeadsUpTab headsUpTable = new HeadsUpTab(0, this);

	public TypeInfo typeInfo;

	public int[] getActiveTypes() {
		return analysisTab.getActiveTypes();
	}

	public String[] getActiveWhere() {
		return analysisTab.getActiveWhere();
	}

	public int[] getAllTypes() {
		return types;
	}

	public String getFieldName(int field) {
		String temp = "Unknown";
		switch (field) {
		case FIELD_SRC_IP:
			temp = "Source IP";
			break;
		case FIELD_DST_IP:
			temp = "Destination IP";
			break;
		case FIELD_START_TS:
			temp = "Start Timestamp";
			break;
		case FIELD_DST_PORT:
			temp = "Destination Port";
			break;
		case FIELD_PROTOCOL:
			temp = "Protocol";
			break;
		}
		return temp;
	}

	public String getQueryID() {
		return analysisTab.getQueryID();
	}

	public int[] getSelectedTypes() {
		return searchTab.getTypes();
	}

	public String getTypeName(int type) {
		return typeNames[typeIdxs[type]];
	}

	private void initTypes() {

		ConfigServiceAsync NetFSEService = (ConfigServiceAsync) GWT
				.create(ConfigService.class);

		ServiceDefTarget endpoint = (ServiceDefTarget) NetFSEService;
		endpoint.setServiceEntryPoint(CONFIG_URL);

		AsyncCallback callback = new AsyncCallback() {
			public void onFailure(Throwable caught) {
				MessageBox.alert("Interface initialization failed: '"
						+ caught.getMessage() + "'");
			}

			public void onSuccess(Object result) {
				setTypes((TypeInfo) result);
			}
		};

		NetFSEService.getTypeInfo(callback);

	}

	public void myQueries() {
		searchResultsTab.myQueries();
	}

	public void onModuleLoadClassic(String queryID) {
		
		// tabsClassic = new com.google.gwt.user.client.ui.TabPanel();

		analysisTab = new AnalysisTab(this);

		searchTab = new SearchTab(this);

		searchHistoryTab = new SearchHistoryTab(this);

		timelineTab = new TimelineTab(this);

		searchResultsTab = new SearchResultsTab(this);

		// tabsClassic.setWidth("100%");
		// tabsClassic.setHeight("100%");

		Panel searchPanel = new Panel();
		searchPanel.setTitle("Search");
		searchPanel.setHeight("auto");
		// searchPanel.setLayout(new BorderLayout());
		searchPanel.add(searchTab, new BorderLayoutData(
				com.gwtext.client.core.RegionPosition.CENTER));
		tabs.add(searchPanel);

		Panel searchResultsPanel = new Panel();
		searchResultsPanel.setHeight("auto");
		searchResultsPanel.setTitle("Results");
		// searchResultsPanel.setLayout(new BorderLayout());
		searchResultsPanel.add(searchResultsTab, new BorderLayoutData(
				com.gwtext.client.core.RegionPosition.CENTER));
		tabs.add(searchResultsPanel);

		Panel analysisPanel = new Panel();
		analysisPanel.setTitle("Analysis");
		analysisPanel.setHeight("auto");
		// analysisPanel.setLayout(new BorderLayout());
		analysisPanel.add(analysisTab, new BorderLayoutData(
				com.gwtext.client.core.RegionPosition.CENTER));
		tabs.add(analysisPanel);

		Panel timelinePanel = new Panel();
		timelinePanel.setTitle("Timeline");
		timelinePanel.setHeight("auto");
		timelinePanel.add(timelineTab, new BorderLayoutData(
				com.gwtext.client.core.RegionPosition.CENTER));
		tabs.add(timelinePanel);

		Panel historyPanel = new Panel();
		historyPanel.setTitle("History");
		historyPanel.setHeight("auto");
		historyPanel.add(searchHistoryTab, new BorderLayoutData(
				com.gwtext.client.core.RegionPosition.CENTER));
		tabs.add(historyPanel);

		headsUpTable.setTitle("Heads Up");
		headsUpTable.setHeight("auto");
		tabs.add(headsUpTable, new BorderLayoutData(
				com.gwtext.client.core.RegionPosition.CENTER));

		Panel configurationPanel = new Panel();
		configurationPanel.setTitle("Configuration");
		configurationPanel.setHeight("auto");
		configurationPanel.add(configurationTab, new BorderLayoutData(
				com.gwtext.client.core.RegionPosition.CENTER));
		tabs.add(configurationPanel);

		// tabsClassic.add(searchTab, "Search");
		// tabsClassic.add(searchResultsTab, "Results");
		// tabsClassic.add(analysisTab, "Analysis");
		// tabsClassic.add(timelineTab, "Timeline");
		// tabsClassic.add(searchHistoryTab, "History");

		// tabsClassic.add(headsUpTable, "Heads Up");
		// tabsClassic.add(configurationTab, "Configuration");

		/*
		 * tabsClassic.addTabListener(new TabListener() {
		 * 
		 * public boolean onBeforeTabSelected(SourcesTabEvents events, int idx)
		 * { return true; }
		 * 
		 * public void onTabSelected(SourcesTabEvents events, int idx) {
		 * 
		 * if (idx == 0) { // New Query } else if (idx == 1) { // Results
		 * myQueries(); } else if (idx == 2) { // Analysis } else if (idx == 3)
		 * { // Timeline } else if (idx == 4) { queryHistory(); } else if (idx
		 * == 5) { // stats(); }
		 * 
		 * // addHistory("tab" + idx); } });
		 */
		FlexTable headerTable = new FlexTable();

		int idx = -1;
		// headerTable.setHTML(++idx, 0, "<b>Status:</b>");
		// headerTable.getFlexCellFormatter().setStyleName(idx, 0, "tdright");

		// headerTable.setWidget(idx, 1, statusLabel);

		// headerTable.setHTML(++idx, 0, "<b>Links:</b>");
		// headerTable.getFlexCellFormatter().setStyleName(idx, 0, "tdright");
		FlexTable linksTable = new FlexTable();
		Hyperlink helpLink = new Hyperlink("Help", "Help");
		helpLink.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent sender) {
				String url = "help.html";
				Window.open(url, "Help", "");
			}
		});

		Hyperlink bugLink = new Hyperlink("Bug Report", "BugReport");
		bugLink.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent sender) {
				String url = "http://www.packetanalytics.com/bugreport.php";
				Window.open(url, "Bug Report", "");
			}
		});

		Hyperlink communityLink = new Hyperlink("User Community",
				"UserCommunity");
		communityLink.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent sender) {
				String url = "http://www.netfse.org/support/";
				Window.open(url, "User Community", "");
			}
		});

		Hyperlink openQueryLink = new Hyperlink("Open Search", "OpenSearch");
		openQueryLink.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent sender) {
				MessageBox.prompt("Open Search",
						"Please enter the ID of the search to open:",
						new MessageBox.PromptCallback() {
							public void execute(String btnID, String text) {
								if (btnID.equals("ok")) {
									openQuery(text);
								}
							}
						});
			}
		});

		Hyperlink setPasswordLink = new Hyperlink("Set Password", "SetPassword");
		setPasswordLink.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent sender) {
				SetPasswordDialogBox setPasswordDialog = new SetPasswordDialogBox();
				setPasswordDialog.reset();
				setPasswordDialog.show();
			}
		});

		int linkIdx = -1;
		linksTable.setWidget(0, ++linkIdx, helpLink);
		linksTable.setWidget(0, ++linkIdx, new Label("|"));
		linksTable.setWidget(0, ++linkIdx, openQueryLink);
		linksTable.setWidget(0, ++linkIdx, new Label("|"));
		linksTable.setWidget(0, ++linkIdx, setPasswordLink);
		linksTable.setWidget(0, ++linkIdx, new Label("|"));
		linksTable.setWidget(0, ++linkIdx, bugLink);
		linksTable.setWidget(0, ++linkIdx, new Label("|"));
		linksTable.setWidget(0, ++linkIdx, communityLink);
		linksTable.setWidget(0, ++linkIdx, new Label("|"));
		linksTable.setHTML(0, ++linkIdx,
				"<a href=\"j_acegi_logout\">Log Out</a>");

		headerTable.setWidget(++idx, 1, linksTable);

		FlexTable mainTable = new FlexTable();
		mainTable.setWidth("100%");
		mainTable.setHeight("100%");
		mainTable.setWidget(0, 0, headerTable);
		// mainTable.setWidget(1, 0, tabsClassic);
		mainTable.setWidget(1, 0, tabs);

		RootPanel.get("slot1").add(mainTable);
		// RootPanel.get("slot2").add(label);

		initTypes();

		// tabsClassic.selectTab(0);
		tabs.activate(0);

		if (queryID.length() > 0)
			analysisTab.openQuery(queryID);
	}

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {

		String queryID = "";
		RootPanel temp = RootPanel.get("queryid");
		if (temp != null) {
			String[] tokens = temp.getElement().toString().split(" ");
			for (int i = 0; i < tokens.length; i++) {
				if (tokens[i].startsWith("value=")) {
					queryID = tokens[i].substring(tokens[i].indexOf("\"") + 1,
							tokens[i].length() - 1);
					if (queryID.endsWith("\""))
						queryID = queryID.substring(0, queryID.length() - 1);
					// Window.alert(queryID);
					break;
				}
			}

		}

		temp = RootPanel.get("uimode");
		if (temp != null) {
			String value = temp.getElement().getPropertyString("value");
			if (value.equals("classic")) {
				UI_MODE = UI_MODE_CLASSIC;
			} else {
				// UI_MODE = UI_MODE_EXT;
			}
		}

		tabs = new com.gwtext.client.widgets.TabPanel();
		tabs.setResizeTabs(true);
		tabs.setMinTabWidth(115);
		tabs.setTabWidth(135);
		tabs.setBorder(true);

		if (UI_MODE == UI_MODE_CLASSIC) {
			onModuleLoadClassic(queryID);
			return;
		}

		initTypes();
//
		// String initToken = History.getToken();
		// if (initToken.length() == 0)
		// initToken = "start";
		// onHistoryChanged(initToken);
		// History.addHistoryListener(this);

		com.gwtext.client.widgets.Button helpBtn = new com.gwtext.client.widgets.Button(
				"Help");
		helpBtn.addListener(new ButtonListenerAdapter() {
			public void onClick(com.gwtext.client.widgets.Button button,
					com.gwtext.client.core.EventObject e) {
				String url = "help.html";
				Window.open(url, "Help", "");
			}
		});

		com.gwtext.client.widgets.Button bugBtn = new com.gwtext.client.widgets.Button(
				"Feedback");
		bugBtn.addListener(new ButtonListenerAdapter() {
			public void onClick(com.gwtext.client.widgets.Button button,
					com.gwtext.client.core.EventObject e) {
				String url = "http://www.packetanalytics.com/bugreport.php";
				Window.open(url, "Bug Report", "");
			}
		});

		com.gwtext.client.widgets.Button communityBtn = new com.gwtext.client.widgets.Button(
				"User Community");
		communityBtn.addListener(new ButtonListenerAdapter() {
			public void onClick(com.gwtext.client.widgets.Button button,
					com.gwtext.client.core.EventObject e) {
				String url = "http://www.packetanalytics.com/community/";
				Window.open(url, "User Community", "");
			}
		});

		com.gwtext.client.widgets.Button openQueryBtn = new com.gwtext.client.widgets.Button(
				"Open Search");
		openQueryBtn.addListener(new ButtonListenerAdapter() {
			public void onClick(com.gwtext.client.widgets.Button button,
					com.gwtext.client.core.EventObject e) {
				MessageBox.prompt("Open Search",
						"Please enter the ID of the search to open:",
						new MessageBox.PromptCallback() {
							public void execute(String btnID, String text) {
								if (btnID.equals("ok")) {
									openQuery(text);
								}
							}
						});
			}
		});

		com.gwtext.client.widgets.Button setPasswordBtn = new com.gwtext.client.widgets.Button(
				"Set Password");
		setPasswordBtn.addListener(new ButtonListenerAdapter() {
			public void onClick(com.gwtext.client.widgets.Button button,
					com.gwtext.client.core.EventObject e) {
				SetPasswordDialogBox setPasswordDialog = new SetPasswordDialogBox();
				setPasswordDialog.reset();
				setPasswordDialog.show();
			}
		});

		Panel logoPanel = new Panel();
		logoPanel.setHtml("<img src=\"image/netfselogo.png\"/>");
		logoPanel.setBorder(false);

		Panel topPanel = new Panel();
		topPanel.setLayout(new VerticalLayout());
		topPanel.setBorder(false);
		topPanel.add(logoPanel);
		topPanel.setHeight(100);

		Panel buttonPanel = new Panel();
		buttonPanel.setPaddings(5);
		buttonPanel.setBorder(false);
		buttonPanel.setLayout(new HorizontalLayout(5));
		buttonPanel.add(helpBtn);
		buttonPanel.add(bugBtn);
		buttonPanel.add(communityBtn);
		// buttonPanel.add(datasetBtn);
		// buttonPanel.add(testBtn);
		buttonPanel.add(openQueryBtn);
		buttonPanel.add(setPasswordBtn);
		topPanel.add(buttonPanel);

		Panel panel = new Panel();
		panel.setBorder(false);
		panel.setPaddings(15);
		panel.setLayout(new com.gwtext.client.widgets.layout.FitLayout());

		Panel mainPanel = new Panel();
		mainPanel.setBorder(false);
		mainPanel.setLayout(new BorderLayout());

		mainPanel.add(topPanel, new BorderLayoutData(
				com.gwtext.client.core.RegionPosition.NORTH));
		mainPanel.add(tabs, new BorderLayoutData(
				com.gwtext.client.core.RegionPosition.CENTER));

		panel.add(mainPanel);

		Viewport viewport = new com.gwtext.client.widgets.Viewport(panel);
		viewport.doLayout();

		// this.tellAnalysisContainerTypesAreHere();

	}

	public void onPopupClosed(PopupPanel sender, boolean autoClosed) {

		try {
			OpenQueryDialogBox oqdb = (OpenQueryDialogBox) sender;
			if (!oqdb.isCancelled()) {
				analysisTab.openQuery(oqdb.getQueryID());
			}
		} catch (ClassCastException cce) {

		}

	}

	public void openQuery(String queryID) {
		// tabsClassic.selectTab(2);
		tabs.activate(2);
		analysisTab.openQuery(queryID);
	}

	public void queryHistory() {
		// searchHistoryTab.queryHistory();
	}

	public void removeConfigs() {
		Component[] components = tabs.getComponents();
		for (int i = 0; i < components.length; i++) {
			Panel temp = (Panel) components[i];
			if (temp.getTitle().equals("Configuration")) {
				tabs.remove(temp.getId());
				break;
			}
		}
	}

	public void setSearchCriteria(QueryOptions qo) {

		searchTab.setSearchCriteria(qo);
		tabs.activate(0);

	}

	private void setTypes(TypeInfo typeInfo) {
		this.typeInfo = typeInfo;
		int numTypes = typeInfo.getNumTypes();
		int maxType = -1;

		this.types = new int[numTypes];
		this.typeIdxs = new int[numTypes];
		this.typeNames = new String[numTypes];

		int[] types = typeInfo.getTypes();
		for (int i = 0; i < numTypes; i++) {
			if (maxType < types[i])
				maxType = types[i];
		}

		this.typeIdxs = new int[maxType + 1];
		for (int i = 0; i < numTypes; i++) {
			final int type = types[i];
			typeIdxs[type] = i;

			this.types[i] = type;
			this.typeNames[i] = typeInfo.getTypeName(types[i]);

		}

		searchTab.setTypes(typeInfo);

		analysisTab.setTypes(typeInfo);

		configurationTab.sensorConfigsTable.setTypes(typeInfo);

		queryHistory();
		myQueries();

	}

}
